/**
 * 案件自动入库和审查流程API
 */

// 模拟案件办结后自动入库的API
export const autoAddCaseToLibrary = async (caseData) => {
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 创建案例库条目
    const libraryCase = {
      id: Date.now(),
      title: caseData.title,
      category: caseData.category,
      author: caseData.lawyer,
      status: 'pending_review', // 自动设置为待审查状态
      caseEndType: caseData.endType, // 判决、调解、和解等
      sensitiveStatus: 'pending_desensitization', // 待脱敏
      visibleTo: ['审核管理员'], // 默认只有审核管理员可见
      views: 0,
      likes: 0,
      createdAt: new Date().toISOString().split('T')[0],
      summary: caseData.summary,
      tags: caseData.tags || [],
      isRecommended: false,
      autoAddedAt: new Date().toLocaleString(),
      // 案件基础信息
      amount: caseData.amount,
      completedAt: caseData.completedAt,
      // 审查流程相关
      reviewStatus: 'pending_review',
      desensitizeProgress: 0,
      waitingDays: 0,
      isUrgent: caseData.amount > 500000, // 金额超过50万标记为紧急
      // 敏感信息识别（AI预处理）
      sensitiveItems: identifySensitiveInfo(caseData.content),
      // 审查历史
      reviewHistory: [
        {
          id: 1,
          action: '案件自动入库',
          operator: '系统',
          timestamp: new Date().toLocaleString(),
          comment: '案件办结后自动进入审查流程'
        }
      ]
    }
    
    console.log('案件自动入库成功:', libraryCase)
    
    return {
      success: true,
      data: libraryCase,
      message: '案件已自动入库，进入待审查阶段'
    }
  } catch (error) {
    console.error('案件自动入库失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 模拟AI识别敏感信息
const identifySensitiveInfo = (content) => {
  const sensitivePatterns = [
    {
      type: '身份证号',
      pattern: /\d{17}[\dX]/g,
      maskMethod: (match) => match.substring(0, 6) + '***********'
    },
    {
      type: '手机号',
      pattern: /1[3-9]\d{9}/g,
      maskMethod: (match) => match.substring(0, 3) + '****' + match.substring(7)
    },
    {
      type: '车牌号',
      pattern: /[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5}/g,
      maskMethod: (match) => match.substring(0, 2) + '***' + match.substring(5)
    },
    {
      type: '银行卡号',
      pattern: /\d{16,19}/g,
      maskMethod: (match) => match.substring(0, 4) + '****' + '****' + match.substring(-4)
    }
  ]
  
  const sensitiveItems = []
  let itemId = 1
  
  sensitivePatterns.forEach(pattern => {
    const matches = content.match(pattern.pattern)
    if (matches) {
      matches.forEach(match => {
        sensitiveItems.push({
          id: itemId++,
          type: pattern.type,
          original: match,
          masked: pattern.maskMethod(match),
          status: 'pending'
        })
      })
    }
  })
  
  return sensitiveItems
}

// 模拟系统脱敏处理API
export const startDesensitization = async (caseId) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    return {
      success: true,
      message: '开始脱敏处理',
      processId: `desensitize_${caseId}_${Date.now()}`
    }
  } catch (error) {
    return {
      success: false,
      error: error.message
    }
  }
}

// 模拟脱敏进度查询API
export const getDesensitizationProgress = async (processId) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    
    // 模拟随机进度
    const progress = Math.floor(Math.random() * 100)
    
    return {
      success: true,
      data: {
        progress,
        status: progress === 100 ? 'completed' : 'processing',
        message: progress === 100 ? '脱敏处理完成' : '脱敏处理中...'
      }
    }
  } catch (error) {
    return {
      success: false,
      error: error.message
    }
  }
}

// 模拟人工审查通过API
export const approveCase = async (caseId, comment = '') => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    return {
      success: true,
      message: '案件审查通过，已正式入库',
      data: {
        status: 'approved',
        approvedAt: new Date().toLocaleString(),
        comment
      }
    }
  } catch (error) {
    return {
      success: false,
      error: error.message
    }
  }
}

// 模拟人工审查拒绝API
export const rejectCase = async (caseId, reason, comment = '') => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    return {
      success: true,
      message: '案件已拒绝入库',
      data: {
        status: 'rejected',
        rejectedAt: new Date().toLocaleString(),
        reason,
        comment
      }
    }
  } catch (error) {
    return {
      success: false,
      error: error.message
    }
  }
}

// 模拟获取待审查案件列表API
export const getPendingReviewCases = async (filters = {}) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 模拟案件数据
    const mockCases = [
      {
        id: 1001,
        title: '多车连环追尾交通事故赔偿案',
        caseType: 'traffic',
        lawyer: '张律师',
        completedAt: '2024-02-15',
        reviewStatus: 'pending_review',
        desensitizeProgress: 0,
        waitingDays: 3,
        isUrgent: true,
        amount: 850000
      },
      {
        id: 1002,
        title: '工伤赔偿劳动争议案',
        caseType: 'labor',
        lawyer: '李律师',
        completedAt: '2024-02-14',
        reviewStatus: 'desensitizing',
        desensitizeProgress: 65,
        waitingDays: 4,
        isUrgent: false,
        amount: 320000
      },
      {
        id: 1003,
        title: '房屋买卖合同纠纷案',
        caseType: 'property',
        lawyer: '王律师',
        completedAt: '2024-02-13',
        reviewStatus: 'manual_review',
        desensitizeProgress: 100,
        waitingDays: 5,
        isUrgent: false,
        amount: 1200000
      }
    ]
    
    // 应用筛选条件
    let filteredCases = mockCases
    
    if (filters.status) {
      filteredCases = filteredCases.filter(c => c.reviewStatus === filters.status)
    }
    
    if (filters.caseType) {
      filteredCases = filteredCases.filter(c => c.caseType === filters.caseType)
    }
    
    if (filters.urgency) {
      if (filters.urgency === 'urgent') {
        filteredCases = filteredCases.filter(c => c.isUrgent)
      } else if (filters.urgency === 'normal') {
        filteredCases = filteredCases.filter(c => !c.isUrgent)
      }
    }
    
    return {
      success: true,
      data: {
        cases: filteredCases,
        total: filteredCases.length,
        stats: {
          pendingReview: mockCases.filter(c => c.reviewStatus === 'pending_review').length,
          desensitizing: mockCases.filter(c => c.reviewStatus === 'desensitizing').length,
          reviewing: mockCases.filter(c => c.reviewStatus === 'manual_review').length,
          approved: 156
        }
      }
    }
  } catch (error) {
    return {
      success: false,
      error: error.message
    }
  }
}

// 模拟案件办结触发器（用于演示）
export const simulateCaseCompletion = async (caseData) => {
  try {
    console.log('案件办结，触发自动入库流程...', caseData)
    
    // 1. 案件办结
    console.log('✅ 案件办结完成')
    
    // 2. 自动入库
    const autoAddResult = await autoAddCaseToLibrary(caseData)
    if (!autoAddResult.success) {
      throw new Error('自动入库失败: ' + autoAddResult.error)
    }
    console.log('✅ 案件自动入库成功')
    
    // 3. 进入待审查阶段
    console.log('✅ 案件进入待审查阶段')
    
    // 4. 通知管理员
    console.log('✅ 已通知管理员进行审查')
    
    return {
      success: true,
      message: '案件办结流程完成，已自动入库等待审查',
      data: autoAddResult.data
    }
  } catch (error) {
    console.error('案件办结流程失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 导出所有API函数
export default {
  autoAddCaseToLibrary,
  startDesensitization,
  getDesensitizationProgress,
  approveCase,
  rejectCase,
  getPendingReviewCases,
  simulateCaseCompletion
}

